<?php

namespace App\Http\Controllers\Serve;

use App\Http\Controllers\Controller;
use App\Models\User;
use Exception;
use Illuminate\Http\Request;

class RegServe extends BaseServe
{
    public $normal_rules;
    public $normal_message;

    const USER_NAME_EXIST = 1001;
    const USER_NAME_OR_PASSWORD_NOT_RIGHT = 1002;


    // const USER_PASSWORD_NOT_SAME = 1003;

    public function __construct(Request $request)
    {
        parent::__construct($request);
        $this->normal_rules = [
            'user_name' => [
                "required",
                "regex:/^[a-z|A-Z][a-z|A-Z|0-9|_]{5,19}$/",
            ],
            'user_password' => "required",
            'user_re_password' => "required|same:user_password",
        ];
        $this->normal_message = [
            'user_name' => trans('user.USER_NAME_FORMAT_ERROR', [], $request->getLocale()),
            'user_password' => trans('user.USER_PASSWORD_FORMAT_ERROR', [], $request->getLocale()),
            'user_re_password' => trans('user.USER_PASSWORD_NOT_SAME', [], $request->getLocale()),
        ];
    }


    /**
     * @param array $data
     * @return bool
     * @throws Exception
     */
    public function normal(array $data): bool
    {
        $this->validate($data, $this->normal_rules, $this->normal_message);
        $this->isNotExit('user_name', $data['user_name']);

        $model = new User();
        $model->user_name = $data['user_name'];
        $model->user_password = password_hash($data['user_password'], PASSWORD_DEFAULT);
        return $model->save();
    }

    /**
     * 如果指定 Key 对应的值存在则抛出错误
     * @param $key
     * @param $value
     * @throws Exception
     */
    public function isNotExit($key, $value)
    {
        if ($this->findByKey($key, $value)) {
            throw new Exception(trans('user.USER_NAME_EXIST', [], 'zh-CN'), self::USER_NAME_EXIST);
            // throw new Exception(trans('user.USER_NAME_EXIST', [], $this->locale), self::USER_NAME_EXIST);
        }
    }

    /**
     * 如果指定 Key 对应的值不存在则抛出错误
     * @param $key
     * @param $value
     * @throws Exception
     */
    public function isExit($key, $value)
    {
        if (!$this->findByKey($key, $value)) {
            throw new Exception(trans('user.USER_NAME_OR_PASSWORD_NOT_RIGHT', [], $this->locale), self::USER_NAME_OR_PASSWORD_NOT_RIGHT);
        }
    }

    public function findByKey($key, $value)
    {
        return User::where($key, $value)->first();
    }
}
